// pages/organize/organize.js
import OrganizeApi from "../../api/organize";
import MyInfoApi from '../../api/myInfo'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    radio:'1',
    code:'',
    type:'',
    userId:'',
    orgId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const type = options.type
    // register  \ userInfo
    const organizeCode = wx.getStorageSync('organizeCode')
    this.setData({
      code:organizeCode,
      type
    })
    if(type == 'userInfo') {
      this.setData({
        userId:options.userId
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  handlerGobackClick(){
    wx.navigateBack()
  },
  /**
   * 扫码
   */
  goToScan(){
    let _this = this
    wx.scanCode({
      success (res) {
        console.log(res)
        const code = res.result
        _this.setData({
          code:code
        })
      }
    })
  },
  /**
   * 确定
   */
  async enter(){
    const code = this.data.code
    if(code == ''){
        wx.showToast({
          title: '请输入机构代码或扫码',
          icon: 'none',
          duration: 2000
      })
      return
    }
    //调用接口
    const param = {
      organCode:this.data.code
    }
    const res = await OrganizeApi.organCodeCheck(param)
    if(res.code == 100){
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000
      })
    }else{
      //判断是否是个人信息修改组织机构
      if(this.data.type == 'userInfo'){
        //调用修改组织机构接口
        const param1 = {
          id: this.data.userId,
          organId: res.data.id
        }
        const res1 = await MyInfoApi.updatePersonalInfor(param1)
        if(res1.code == 100){
          wx.showToast({
            title: res1.message,
            icon: 'none',
            duration: 2000
          })
        }else {
          wx.setStorageSync('organizeCode',this.data.code)
          wx.setStorageSync('organizeName',res.data.organName)
          //跳回上一页
          wx.navigateBack()
        }
      }else {
        //storage 中存入数据
        wx.setStorageSync('organizeCode',this.data.code)
        wx.setStorageSync('organizeName',res.data.organName)
        //跳回上一页
        wx.navigateBack()
      }
    }
  },
  /**
   * input 数据绑定
   */
  updateValue(e) {
    let name = e.currentTarget.dataset.name;
    let nameMap = {}
    nameMap[name] = e.detail.value
    this.setData(nameMap)
  },
})
